﻿//void Print(int n, int i)
//{
//
//}
//
//int main()
//{
//	thread t1(Print, 10, 0);
//	thread t2(Print, 20, 10);
//	//获取线程id
//	cout << t1.get_id() << endl;
//	cout << t2.get_id() << endl;
//	//...
//	t1.join();
//	t2.join();
//}

#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
#include<vector>

static int name = 1;
void test1()
{
	int ticketnum = 100;
	mutex mtx;
	auto BuyTicket = [&mtx, &ticketnum](int name) {
		/*lock_guard<mutex> lockguard(mtx);*/
		while (true)
		{
			{
				// 使用 lock_guard 管理互斥锁
				lock_guard<mutex> lockguard(mtx);
				if (ticketnum <= 0) {
					//如果没这个判断，可能这个线程还没有退出，很多线程就全部进来 --，导致数据会变成负数
					break;
				}
				ticketnum--;
				cout << "我是线程 " << name << " 我购买了一张票;" << "还剩下票: " << ticketnum << "张" << endl;
			}
		}
	};

	vector<thread>t(100);
	for (auto& thr : t)
	{
		thr = thread(BuyTicket, name++);
	}

	for (auto& thr : t)
	{
		thr.join();
	}
}

#include<condition_variable>
//两个线程 交替打印 奇数与偶数
void test2()
{
	mutex mtx;
	condition_variable c;
	int n = 100;
	bool flag = true;

	//第一个打印的是t1打印0
	thread t1([&]() {
		int i = 0;
		while (i < n)
		{
			unique_lock<mutex> lock(mtx);
			while (!flag)
			{
				c.wait(lock);
			}
			cout << i << endl;

			flag = false;
			i += 2;//偶数

			c.notify_one();
		}
		});

	this_thread::sleep_for(chrono::seconds(1));
	thread t2([&]() {
		int j = 1;
		while (j < n)
		{
			unique_lock<mutex> lock(mtx);

			// 只要flag == true t2⼀直阻塞
			// 只要flag == false t2不会阻塞
			while (flag)
				c.wait(lock);

			cout << j << endl;
			j += 2;
			flag = true;

			c.notify_one();
		}
		});

	t1.join();
	t2.join();
}

int main()
{
	test2();
}